package com.mall.interceptor;
import com.google.gson.Gson;
import com.mall.annotation.AdminLimit;
import com.mall.annotation.LoginToken;
import com.mall.annotation.MangerLimit;
import com.mall.dto.ActionResult;
import com.mall.dto.VSys_user;
import com.mall.service.Sys_userService;
import com.mall.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * @Author zhanggaoxiang
 * @Description 全局权限拦截器
 * @Date 2021/1/7 13:45
 * @Param
 * @return
 **/
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {
    @Autowired
    private Sys_userService sys_userService;

    /**
     * 事前（进入接口方法前）处理
     *
     * @param request
     * @param response
     * @param handler  代理的方法对象
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info("---------请求路径：" + requestURI);
        String token = request.getHeader("token");
        log.info("---------token：" + token);
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //获取拦截的方法
        HandlerMethod hm = (HandlerMethod) handler;
        Method method = hm.getMethod();
        if (method.isAnnotationPresent(LoginToken.class)) {  //方法前含有指定的注解，需要验证token
            boolean checkToken = JwtUtils.checkToken(token);
            log.info("===========" + token + ":" + checkToken);
            if (checkToken) {
                return true;
            } else {
                ActionResult actionResult = new ActionResult(403, "token invalid!!!", null);
                String json = new Gson().toJson(actionResult);
                PrintWriter out = response.getWriter();
                response.setHeader("contentType", "application/json");
                out.write(json);
                return false;
            }
        }
        //超级管理员的权限
        if (method.isAnnotationPresent(AdminLimit.class)){
            String username = JwtUtils.getUserName(token);
            VSys_user vSys_user = sys_userService.findUserRoleByUsername(username);
            if (vSys_user.getRole_name()!="超级管理员" && !requestURI.equals(vSys_user.getMenu_url())){
                ActionResult actionResult = new ActionResult(403, "权限不足!!!!", null);
                String json = new Gson().toJson(actionResult);
                PrintWriter out = response.getWriter();
                response.setHeader("contentType","application/json");
                out.write(json);
                return false;
            }else {
                return true;
            }
        }
        //普通管理员的权限
        if (method.isAnnotationPresent(MangerLimit.class)){
            String username = JwtUtils.getUserName(token);
            VSys_user vSys_user = sys_userService.findUserRoleByUsername(username);
            if (vSys_user.getRole_name()!="管理员" && !requestURI.equals(vSys_user.getMenu_url())){
                ActionResult actionResult = new ActionResult(403, "权限不足!!!!", null);
                String json = new Gson().toJson(actionResult);
                PrintWriter out = response.getWriter();
                response.setHeader("contentType","application/json");
                out.write(json);
                return false;
            }else {
                return true;
            }
        }
        return true;
    }


//事后（执行完接口逻辑，未进入视图解析器前）
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
// 解析完返回视图
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
